import Vue from 'vue'

import VueRouter from 'vue-router'
import Login from '../views/login'
import Index from '../views/index'
import Welcome from '../views/welcome'
import Postlist from '../views/postlist'
import PostPublish from '../views/postPublish'
import UserList from '../views/userList'
import CateList from '../views/cateList'

Vue.use(VueRouter)
let router = new VueRouter({
  routes: [
    {
      name: 'Login',
      path: '/login',
      component: Login
    },
    {
      name: 'Index',
      path: '/',
      component: Index,
      redirect: { name: 'Welcome' },
      children: [
        {
          name: 'Welcome',
          path: 'welcome',
          component: Welcome
        },
        //  实现路由的复用(发表文章和编辑文章)
        {
          name: 'Postlist',
          path: 'postlist',
          component: Postlist
        },
        {
          name: 'PostPublish',
          path: 'postPublish/:id?',
          component: PostPublish
        },
        {
          name: 'UserList',
          path: 'userList',
          component: UserList
        },
        {
          name: 'CateList',
          path: 'cateList',
          component: CateList
        }
      ]
    }
  ]
})

// 增加导航守卫
router.beforeEach((to, from, next) => {
  if (to.path === '/login') {
    next()
  } else {
    if (localStorage.getItem('heima_toutiao_token')) {
      next()
    } else {
      next({ name: 'Login' })
    }
  }
})

export default router
